import datetime
import logging
import random
import sys
import time

import accountApi
import config
import requests
from DB import MySQLUtils


def getHouses(conf, count):
    """查询房源信息

    Args:
        conf (Object): 配置项
        count (int): 数量

    Returns:
        list: 房源集和
    """
    dbUtil = MySQLUtils.DBUtil()
    # logging.info(dbUtil.__dict__)

    houses = []
    for section, max_count in conf["section"].items():
        sql = f"select * from house where section = '{section}' and is_del = 0 order by create_time desc limit {max_count};"
        result = dbUtil.get_all(sql)

        if result:
            houses.extend(dbUtil.get_all(sql))

            if (len(houses) >= count):
                # 截取数据
                if (len(houses) > count):
                    houses = houses[:count]

                logging.info(f"小区 {section} 将爬取 {len(houses)} 条数据")
                return houses

    return houses


def getOwnerJson(account, house_id):
    """获取房主信息

    Args:
        account (string): 账号
        house_id (string): 房源id

    Raises:
        ValueError: 在其他地方被登录
        ValueError: 账号超过限制

    Returns:
        jsonObject: 房东对象
    """
    url = f'http://erp.fangline.cn/house/list-house-owner.json?houseId={house_id}'
    response = requests.post(url, headers=accountApi.getHeaders(account))

    if response.status_code == 316:
        raise ValueError(f"账号{account}在其他地方被登录")

    if ("msg" in response.json()):
        raise ValueError(f"账号{account} {response.json()['msg']}")
    
    return response.json()


def pushFollow(token, user, house_id):
    """提交跟进记录

    Args:
        token (string): 登录token
        user (string): 账号
        house_id (string): 房源id
    """
    content = random.choice(config.executorParams["flowerText"])

    url = f'http://erp.fangline.cn/house/writeFollowUp?houseId={house_id}&content={content}&token={token}&imgs=&deleteTag=true'
    response = requests.post(url, headers=accountApi.getHeaders(user))
    logging.info(f'房源：{house_id} 子账号填写跟进记录:{content},{response.content}')


def saveOwnerAndUpdateHouse(account, house_id):
    """保存房东信息并且更新房源状态

    Args:
        account (string): 账号
        house_id (string): 房源id
    """
    dbUtil = MySQLUtils.DBUtil()

    # 取 owner 信息
    ownerJson = getOwnerJson(account, house_id)
    # 需要提交跟进记录
    if (ownerJson['status'] != '不需要'):
        pushFollow(ownerJson['token'], account, house_id)
    owners = ownerJson['ownerList']
    token = ownerJson['token']

    logging.info(f'房源：{house_id} 房主信息有:{len(owners)}条 token:{token}，ownerJson:{ownerJson}')

    # 保存数据
    for o in ownerJson['ownerList']:
        sql = "INSERT INTO house_owner (owner_id, house_id, owner_name, tel, cityId) VALUES (%s, %s, %s, %s, %s)"
        values = (o['ownerId'], house_id, o['ownerName'], o['tel'], o['cityId'])
        dbUtil.saveAsValues(sql, values)

    updSql = f"update house set is_del = 1,follows_str='{account}' where house_id = {house_id}"
    dbUtil.update(updSql)
    logging.info(f'房源：{house_id} 更新状态为已经获取房东信息')


def main():
    """主函数
    """
    conf = config.executorParams
    logging.info("读取配置文件完毕")

    # 监控每个账号抓取的房源数量
    for user, max_count in conf["user"].items():

        try:
            # 取符合爬取条件的房源列表，按照配置的数量获取
            houses = getHouses(conf, max_count)
            for house in houses:
                house_id = house[0]
                logging.info(f"账号{user}, 将爬取 {house_id} 数据")

                # 获取房东信息
                saveOwnerAndUpdateHouse(user, house_id)

                # 停顿时间
                random_number = random.randint(5, 9)
                if (conf["sleep"]):
                    time.sleep(random_number)
                    
        except Exception as e:
            logging.error(e)

    logging.info(f"任务完成")
    sys.exit()


# 主函数
if __name__ == '__main__':
    current_date = datetime.datetime.now().strftime("%Y%m%d")
    log_file = f"logs/{current_date}.log"
    config.setup_logging(log_file)

    main()
